# config_ehh: the Ehh configuration script.
#
# Copyright (C) 2014 Daniel Gutson, Taller Technologies
#
# This file is part of the Ehh project - the exec hook hacker.
#
# Ehh is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ehh is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with fudepan-build.  If not, see <http://www.gnu.org/licenses/>.

EHH_DIR=~/.ehh
LIBC_CFG=$EHH_DIR/libc.cfg
EHH_CFG=$EHH_DIR/.ehh_rc

function getlibc()
{
    ldd $(which $1)|grep libc|cut -d">" -f2 | cut -d"(" -f1|sed 's/^ *//g'
}

function createEmptyCfg()
{
    cat > $EHH_CFG << EOT
#Syntax:
#program condition_action argument1 [argument2]

#Available condition_action: IF_EXISTS_REPLACE, IF_EXISTS_REMOVE, IF_NOT_EXISTS_ADD
#IF_EXISTS_REPLACE old new
#IF_EXISTS_REMOVE old
#IF_NOT_EXISTS_ADD new

#Uncomment some lines below or add your own
#gcc IF_NOT_EXISTS_ADD -ggdb3
#gcc IF_EXISTS_REMOVE -NDEBUG
#gcc IF_EXISTS_REPLACE -g -ggdb3
#gcc IF_EXISTS_REPLACE -O2 -O0
#gcc IF_EXISTS_REPLACE -O3 -O0
#gcc IF_EXISTS_REPLACE -Os -O0
#gcc IF_NOT_EXISTS_ADD -O0
#g++ IF_NOT_EXISTS_ADD -ggdb3
#g++ IF_EXISTS_REMOVE -NDEBUG
#g++ IF_EXISTS_REPLACE -g -ggdb3
#g++ IF_EXISTS_REPLACE -O2 -O0
#g++ IF_EXISTS_REPLACE -O3 -O0
#g++ IF_EXISTS_REPLACE -Os -O0
#g++ IF_NOT_EXISTS_ADD -O0
EOT
}

function addBin()
{
    echo $1 $(getlibc $1) >> $LIBC_CFG
}

if [ -d $EHH_DIR ]; then
    rm -rf $LIBC_CFG
    if [ -f $EHH_CFG ]; then
        BINARIES=$(grep -v "^$" $EHH_CFG|grep -v "^#" |cut -d" " -f1|sort|uniq)
        if [ -z "$BINARIES" ]; then
            touch $LIBC_CFG
        else
            for BIN in $BINARIES; do
                if [ -f $BIN ]; then
                    addBin $BIN
                else
                    FULLBIN=$(which $BIN)
                    if [ ! -z "$FULLBIN" ]; then
                        addBin $FULLBIN
                    else
                        echo $BIN binary not found. Skipped.
                    fi
                fi
            done
        fi
        echo \* $(getlibc $(which bash)) >> $LIBC_CFG
        RET=0
    else
        echo Missing configuration file $EHH_CFG
        RET=1
    fi
else
    #do initialization stuff
    echo Creating configuration directory $EHH_DIR
    mkdir $EHH_DIR
    echo Creating sample and empty configuration file $EHH_CFG
    createEmptyCfg
    touch $LIBC_CFG
    RET=0
fi

if [ $RET -eq 0 ]; then
    true
else
    false
fi

